package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.qingcheng.dao.SkuMapper;
import com.qingcheng.dao.StockBackMapper;
import com.qingcheng.pojo.goods.StockBack;
import com.qingcheng.pojo.order.OrderItem;
import com.qingcheng.service.goods.StockBackService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Author:boy
 * @Date:2019/7/21
 * @description:
 * @ModifiedBy:
 */
@Service
public class StockBackServiceImpl implements StockBackService {
    @Autowired
    private StockBackMapper stockBackMapper;
    @Autowired
    private SkuMapper skuMapper;

    @Transactional
    public void addList(List<OrderItem> orderItems) {
        for (OrderItem orderItem : orderItems) {
            StockBack stockBack = new StockBack();
            stockBack.setOrderId(orderItem.getOrderId());
            stockBack.setSkuId(orderItem.getSkuId());
            stockBack.setNum(orderItem.getNum());
            stockBack.setCreateTime(new Date());
            stockBack.setStatus("0");
            stockBackMapper.insert(stockBack);
        }
    }

    @Transactional
    public void doBack() {
        StockBack stockBack = new StockBack();
        stockBack.setStatus("0");
        List<StockBack> stockBacks = stockBackMapper.select(stockBack);
        for (StockBack back : stockBacks) {
            //加库存
            skuMapper.decrStore(stockBack.getSkuId(), -stockBack.getNum());
            //减销量
            skuMapper.incrSaleNum(stockBack.getSkuId(), -stockBack.getNum());
            //更新回滚表数据
            back.setStatus("1");
            back.setBackTime(new Date());
            stockBackMapper.updateByPrimaryKey(back);
        }
    }
}
